package com.ai.service.made.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.hash.Hash;
import cn.hutool.core.util.StrUtil;
import com.ai.common.constant.AlgorithmConstant;
import com.ai.common.constant.CommonArgs;
import com.ai.common.CommonResponse;
import com.ai.common.constant.FunctionTypeConstants;
import com.ai.common.constant.PlcConstants;
import com.ai.entity.BasePage;
import com.ai.entity.alarm.*;


import com.ai.entity.function.FunctionPO;
import com.ai.entity.made.RegionBase;
import com.ai.entity.made.camera.CameraPO;
import com.ai.entity.network.IdentifySysToL1Message;
import com.ai.mapper.alarm.RecordAlarmMapper;
import com.ai.model.dto.RecordInfoDto;
import com.ai.model.excelParam.RecordAlarmExcelVo;
import com.ai.model.made.RegionalViolationDto;
import com.ai.model.made.TopFiveViolationsDto;
import com.ai.model.param.AlgorithmAlarmParam;
import com.ai.model.vo.ActualRecordVo;
import com.ai.model.vo.MonthAlarmNumAndDetail;
import com.ai.model.vo.RecordNumAndDetail;
import com.ai.networking.websocket.service.WebSocket;
import com.ai.networking.websocket.service.entity.WSMessage;
import com.ai.service.made.*;
import com.ai.service.rocketMq.RocketMQProducerService;
import com.ai.util.*;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

//import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static com.ai.networking.netty.client.BootNettyClientChannelCache.clientSendMessage;

/**
 * <p>
 * 服务实现类
 *
 * </p>
 *
 * @author Mr.Chen
 * @since 2020-06-19
 */
@Service
@Slf4j
public class RecordAlarmServiceImpl extends ServiceImpl<RecordAlarmMapper, RecordAlarmPO> implements RecordAlarmService {


    @Resource
    IRegionManageService iRegionManageService;

    @Resource
    IRegionBaseService iRegionBaseService;

    @Resource
    RecordAlarmMapper recordAlarmMapper;
    @Resource
    CameraService cameraService;
    @Resource
    FunctionService functionService;

    @Resource
    L2SignalService l2SignalService;

    @Autowired
    private ServerService serverService;

//    @Resource
//    private MsgService msgService;

    @Value("${networkMapping.webServerIp}")
    private String webServerIp;

    @Value("${networkMapping.webServerMappingIp}")
    private String webServerMappingIp;

    @Value("${networkMapping.computingPlatform1Ip}")
    private String computingPlatform1Ip;

    @Value("${networkMapping.computingPlatformMapping1Ip}")
    private String computingPlatformMapping1Ip;

    @Value("${networkMapping.computingPlatform2Ip}")
    private String computingPlatform2Ip;

    @Value("${networkMapping.computingPlatformMapping2Ip}")
    private String computingPlatformMapping2Ip;

    @Value("${exportImportPath.excelPath}")
    private String recordExportPath;

    @Resource
    private GetCameraPlaybackUrlUtil cameraPlaybackUrlUtil;

//    @Autowired
    private RocketMQProducerService rocketMQProducerService;



    @Autowired
    private ISignalRecordService iSignalRecordService;


    private static volatile AtomicInteger FREQUENCY_A3_NUM = new AtomicInteger(0);

//    public static volatile Boolean NOTIFICATIONS_A3 = false;//a3移板机
//
//    public static volatile Boolean TRACK_STACKING = false;//叠钢
//
//    public static volatile Boolean STEEL_INSTALLATION_DEVIATION = false;//装钢偏斜
//    public static volatile Boolean STEEL_DRAWING_DEVIATION = false;//抽钢偏斜
//    public static volatile Boolean FURNACE_DOOR_STATUS =false;//炉门状态
//    public static volatile Boolean RANGING_STEEL = false;//钢板测距
    /**
     *
     * }
     */

    /**
     * 算法提交识别警告
     *
     * @param alarmBOList
     * @return
     */
    @Override
    public CommonResponse addAlarm(List<AlgorithmAlarmBO> alarmBOList) {
        for (AlgorithmAlarmBO algorithmAlarmBO : alarmBOList) {

            if (algorithmAlarmBO.getCameraId() == null || algorithmAlarmBO.getCameraId() == 0) {
                return CommonResponse.error("没有摄像头ID");
            }

            if (StringUtils.isEmpty(algorithmAlarmBO.getSnapPhoto())) {
                return CommonResponse.error("没有抓拍图片");
            }

            if (StringUtils.isEmpty(algorithmAlarmBO.getFunctionType())) {
                return CommonResponse.error("没有警报类型");
            }

            CameraPO cameraPO = cameraService.getById(algorithmAlarmBO.getCameraId());

            if (cameraPO == null) {
                return CommonResponse.error("摄像头不存在");
            }

            SimpleDateFormat sformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//格式
            Date date = new Date();
            try {
                if (!StringUtils.isEmpty(algorithmAlarmBO.getCreateTime())) {
                    date = sformat.parse(algorithmAlarmBO.getCreateTime());
                }
            } catch (ParseException e) {
                log.error("告警日期格式解析失效",e);
            }

            //算法提交的图片为路径
            String webPhotoPath = algorithmAlarmBO.getSnapPhoto();
            String webVideoPath = algorithmAlarmBO.getSnapVideo();


            Integer type = Integer.parseInt(algorithmAlarmBO.getFunctionType());

            //保存违规对象
            RecordAlarmPO alarmPO = new RecordAlarmPO();
            alarmPO.setSnapVideo(algorithmAlarmBO.getSnapVideo());//视频路径
            alarmPO.setCameraId(algorithmAlarmBO.getCameraId());
            alarmPO.setCameraCode(cameraPO.getCode());
            alarmPO.setIsVideo(algorithmAlarmBO.getIsVideo());
            alarmPO.setFunctionType(type);
            alarmPO.setSnapPhoto(webPhotoPath);
            alarmPO.setSnapVideo(webVideoPath);
            alarmPO.setSubgroup(type);
            alarmPO.setCreateTime(date);
            alarmPO.setUpdateTime(date);
            save(alarmPO);

            //煤矿项目，接收到告警之后进行短信推送
            sendMessageToManage(cameraPO,alarmPO);

            sendWebSocket(type);
            algorithmAlarmBO.setSnapPhoto(webPhotoPath);
            algorithmAlarmBO.setSnapVideo(webVideoPath);


        }


        return CommonResponse.ok("警告发送成功");
    }

    /**
     * 发生告警，以短信的形式推送到区域管理人
     * @param cameraPO 摄像头信息
     * @param alarmPO 告警信息
     */
    private void sendMessageToManage(CameraPO cameraPO, RecordAlarmPO alarmPO) {

        //获取当前摄像头管理人员对应的手机号
        RegionBase regionBase = iRegionBaseService.getById(cameraPO.getRegionId());
//        String phone = iRegionManageService.getRegionManagePhone(cameraPO);
        String phone = regionBase.getPhone();
        //获取当前摄像头所在区域的名称
//        String regionName = iRegionManageService.getRegionByCameraId(cameraPO.getId());
        String regionName = regionBase.getRegionName();

        //获取功能名称
        FunctionPO function = functionService.getFunByType(alarmPO.getFunctionType());

        if (org.apache.commons.lang3.StringUtils.isEmpty(phone)){
            log.error("===========================  摄像头：{} 无管理人员对应的手机号  ===========================",cameraPO.getNickname());
        }else {
            String messageContent = regionName + " " + function.getNickname() + "算法识别到异常";
            log.info("===========================    开始发送短信：{}    ===========================",messageContent);
            String sendMessage = CoalTextMessageUtil.SendMessage(phone, messageContent);
            log.info("===========================  短信发送结束 sendMessage   ===========================");

        }

    }


    @Override
//    @Transactional
    public CommonResponse addWarningRecord(AlgorithmAlarmParam algorithmAlarmParams) {

        List<String> alarmParamsTypes = algorithmAlarmParams.getTypes();
        ArrayList<AlgorithmAlarmBO> alarmBOArrayList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(alarmParamsTypes)) {
            for (String type : alarmParamsTypes) {
                AlgorithmAlarmBO algorithmAlarmBO = new AlgorithmAlarmBO();
                //摄像头id
                algorithmAlarmBO.setCameraId(algorithmAlarmParams.getCameraId());
                //功能类型
                algorithmAlarmBO.setFunctionType(type);
                //识别时间
                algorithmAlarmBO.setCreateTime(algorithmAlarmParams.getCreateTime());
                //抓怕图片
                algorithmAlarmBO.setSnapPhoto(algorithmAlarmParams.getSnapPhoto());
                //直播还是录像
                algorithmAlarmBO.setIsVideo(algorithmAlarmBO.getIsVideo());
                //抓拍视频路径
                algorithmAlarmBO.setSnapVideo(algorithmAlarmParams.getSnapVideo());
                alarmBOArrayList.add(algorithmAlarmBO);
            }

            return this.addAlarm(alarmBOArrayList);
        }


        return CommonResponse.error("未携带警告类型");
    }

    /**
     * 向plc发送消息
     *
     * @param signalRecord
     * @param algorithmAlarmBO
     */
    private void sendMsgToPlc(SignalRecord signalRecord, AlgorithmAlarmBO algorithmAlarmBO, String plcCode) {

        String nettyCode = signalRecord.getNettyCode();
        Integer telID = getTelIDByFunType(Integer.parseInt(algorithmAlarmBO.getFunctionType()), signalRecord.getSignalResource());

        IdentifySysToL1Message identifySysToL1Message = new IdentifySysToL1Message();
        identifySysToL1Message.setTelID(telID);//电文号
        identifySysToL1Message.setPlanNo(algorithmAlarmBO.getStripNo());//版批号
        identifySysToL1Message.setDoorNum(algorithmAlarmBO.getDoorNum());//炉门编号
        identifySysToL1Message.setResult(algorithmAlarmBO.getResult());// 1 正常 2 异常
//        identifySysToL1Message.setSpare();
        String jsonString = JSONObject.toJSONString(identifySysToL1Message);
        int length = jsonString.getBytes().length;

        //填充真实数据的字节长度
        identifySysToL1Message.setTelLen(length);

        String msgJSON = JSONObject.toJSONString(identifySysToL1Message);

        clientSendMessage(plcCode, msgJSON);

    }

    public static Integer getTelIDByFunType(Integer funType, String clientIp) {

        Integer telID = 0;

        if (funType.equals(FunctionTypeConstants.A3_TRANSFER_SLAB_DEVIATION)) {
            telID = AlgorithmConstant.A3_TRANSFER_MACHINE_AUTOMATIC_CONFIRMATION;
        } else if (funType.equals(FunctionTypeConstants.SUPERPOSE_STEEL_IDENTIFICATION)) {
            //一个信号开启了两个功能，  那么收到某一个功能的信号识别记录是否需要通知plc
            telID = AlgorithmConstant.TRACK_STACKING_STEEL;

        } else if (funType.equals(FunctionTypeConstants.RANGING_STEEL)) {
            telID = AlgorithmConstant.TRACK_STACKING_STEEL;

        } else if (funType.equals(FunctionTypeConstants.LOAD_STEEL_DEVIATION) && clientIp.equals(PlcConstants.PLC_2_IP)) {
            telID = AlgorithmConstant.STEEL_INSTALLATION_DEVIATION_30_4;

        } else if (funType.equals(FunctionTypeConstants.TAKE_STEEL_DEVIATION) && clientIp.equals(PlcConstants.PLC_2_IP)) {
            telID = AlgorithmConstant.STEEL_DRAWING_DEVIATION_30_4;

        } else if (funType.equals(FunctionTypeConstants.STOVE_STATUS) && clientIp.equals(PlcConstants.PLC_2_IP)) {
            telID = AlgorithmConstant.FURNACE_DOOR_STATUS_30_4;

        } else if (funType.equals(FunctionTypeConstants.LOAD_STEEL_DEVIATION) && clientIp.equals(PlcConstants.PLC_3_IP)) {
            telID = AlgorithmConstant.STEEL_INSTALLATION_DEVIATION_30_5;

        } else if (funType.equals(FunctionTypeConstants.TAKE_STEEL_DEVIATION) && clientIp.equals(PlcConstants.PLC_3_IP)) {
            telID = AlgorithmConstant.STEEL_DRAWING_DEVIATION_30_5;

        } else if (funType.equals(FunctionTypeConstants.STOVE_STATUS) && clientIp.equals(PlcConstants.PLC_3_IP)) {
            telID = AlgorithmConstant.FURNACE_DOOR_STATUS_30_5;

        }
        return telID;
    }


    private void sendWebSocket(int type) {
        WSMessage wsMessage = new WSMessage();
        wsMessage.setContent("UPDATE");

        if (CommonArgs.WS_RECORD_MAP.containsKey(type)
                && CommonArgs.WS_RECORD_MAP.get(type) != null
                && CommonArgs.WS_RECORD_MAP.get(type).size() > 0) {
            CopyOnWriteArraySet<WebSocket> webSockets = CommonArgs.WS_RECORD_MAP.get(type);
            for (WebSocket ws : webSockets) {
                ws.sendMessage(wsMessage);
            }
        }
    }

    private void sendHttp(RecordAlarmPO alarmPO) {


    }


    /**
     * 分页查询
     *
     * @param page
     * @return
     */
    @Override
    public CommonResponse selectByPage(RecordAlarmPage page) {

        IPage<RecordAlarmVO> voIPage = new BasePage<>();

//        //获取当前区域管理的摄像头
//        HashMap<String,String> cameraRegionMap = SecurityUtils.getRegionManageCamerasCode(iRegionBaseService, iRegionManageService);
//        if (CollectionUtils.isEmpty(cameraRegionMap)){
//            //当前区域没有管理任何摄像头
//            return CommonResponse.ok(voIPage);
//        }
//        //获取所有摄像头code
//        if (StringUtils.isEmpty(page.getRegionBaseId())) {
//            ArrayList<String> cameraCodes = new ArrayList<>(cameraRegionMap.keySet());
//            page.setCameraCodes(cameraCodes);
//        }else{
//            CommonResponse bindList = iRegionManageService.getBindList(page.getRegionBaseId());
//            ArrayList<String> bindListData = (ArrayList<String>) bindList.getData();
//            page.setCameraCodes(bindListData);
//        }
//        log.info("===========================  cameraCodes  ===========================,{}",page.getCameraCodes());

        List<String> cameraIdList = new ArrayList<>();
        if (StrUtil.isNotEmpty(page.getRegionBaseId())){
            //获取其组织下的所有摄像头id
            cameraIdList = iRegionManageService.getBelowCameraIdList(page.getRegionBaseId());
        }else {
            //获取当前登录用户下的所有设摄像头id
            cameraIdList = iRegionManageService.getBelowCameraIdList(SecurityUtils.getLoginRegionBaseId());
        }
        if (CollectionUtils.isEmpty(cameraIdList)){
            //当前区域没有管理任何摄像头
            return CommonResponse.ok(voIPage);
        }

        page.setCameraIdList(cameraIdList);

        QueryWrapper<RecordAlarmPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        queryWrapper = page.getQuery(queryWrapper);
        voIPage = recordAlarmMapper.getRecordListQuickly(page, queryWrapper);
        List<RecordAlarmVO> records = voIPage.getRecords();


        for (RecordAlarmVO record : records) {
            if (record.getIsError() == 9) {
                break;
            }
            String name = functionService.getNameByCode(record.getFunctionType());
            CameraPO cameraPO = cameraService.getById(record.getCameraId());
            RegionBase regionBase = iRegionBaseService.getById(cameraPO.getRegionId());
//            String regionCode = cameraRegionMap.get(cameraPO.getCode());
//            RegionBase regionBaseByCode = iRegionBaseService.getRegionBaseByCode(regionCode);
            //区域名
            record.setRegionName(regionBase.getRegionName());
            record.setFunctionNickname(name);
            record.setCameraNickname(cameraPO.getNickname());
        }
        voIPage.setRecords(records);
        return CommonResponse.ok(voIPage);
    }

    /**
     * 是否误报
     *
     * @param recordAlarmBO
     * @return
     */
    @Override
    public CommonResponse signError(RecordAlarmBO recordAlarmBO) {
        RecordAlarmBO alarmBO = new RecordAlarmBO();
        alarmBO.setId(recordAlarmBO.getId());
        alarmBO.setIsError(recordAlarmBO.getIsError());
        alarmBO.setReviewComments(recordAlarmBO.getReviewComments());
        RecordAlarmPO recordAlarmPO = RecordAlarmBO.convertBOToPO(alarmBO);
        if (updateById(recordAlarmPO)) {
            return CommonResponse.ok("标记成功");
        }
        return CommonResponse.error("标记失败");
    }

    @Override
    public List<RecordAlarmPO> getRecordByCameraCodeAndFunType(ArrayList<String> cameraCode, String funType) {

        List<RecordAlarmPO> recordAlarmPOList = recordAlarmMapper.getRecordByCameraCodeAndFunType(cameraCode, funType);

        return recordAlarmPOList;
    }

    @Override
    public List<TopFiveViolationsDto> topFiveViolations() {

        List<TopFiveViolationsDto> topFiveViolationsDtos = this.baseMapper.topFiveViolations();

        return topFiveViolationsDtos;
    }

    @Override
    public List<RegionalViolationDto> regionalViolation() {

        List<RegionalViolationDto> regionalViolationDtoList = this.baseMapper.regionalViolation();

        return regionalViolationDtoList;
    }

    @Override
    public CommonResponse latestRecord() {
        // 获取当前日期
        LocalDate today = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String date = today.format(formatter);

        QueryWrapper<RecordAlarmPO> queryWrapper = new QueryWrapper<>();
        //只获取当天的最新十条
        queryWrapper.ge("create_time", date);
        queryWrapper.orderByDesc("create_time");
        queryWrapper.last("limit 10");
        List<RecordAlarmPO> latestRecordList = this.list(queryWrapper);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// DATE格式化
        ArrayList<ActualRecordVo> recordVoArrayList = new ArrayList<>();

        if (!CollectionUtils.isEmpty(latestRecordList)) {
            for (RecordAlarmPO recordAlarmPO : latestRecordList) {
                //组装实时违规记录字段
                ActualRecordVo actualRecordVo = new ActualRecordVo();

                CameraPO cameraPO = cameraService.getById(recordAlarmPO.getCameraId());

                if (null != cameraPO) {
                    actualRecordVo.setCameraName(cameraPO.getNickname());
                    actualRecordVo.setCameraCode(cameraPO.getCode());
                }
                FunctionPO functionPO = functionService.getFunByType(recordAlarmPO.getFunctionType());
                if (null != functionPO) {
                    actualRecordVo.setFunName(functionPO.getNickname());
                }
                RegionBase regionBase = iRegionBaseService.getRegionByCameraId(cameraPO.getId());
                if (null != regionBase) {
                    actualRecordVo.setRegionName(regionBase.getRegionName());
                }
                actualRecordVo.setViolationTime(simpleDateFormat.format(recordAlarmPO.getCreateTime()));

                recordVoArrayList.add(actualRecordVo);
            }
        }

        return CommonResponse.ok(recordVoArrayList);
    }

    @Override
    public CommonResponse getCameraPlaybackUrl(String recordId) {

        /**
         * 根据告警记录id，查找对应的摄像头
         */
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        RecordAlarmPO recordAlarmPO = this.getById(recordId);

        String serverIp = this.getServerIpByRecord(recordId);

        if (serverIp.equals(webServerIp)) {
            serverIp=webServerMappingIp;
        } else if (serverIp.equals(computingPlatform1Ip)) {
            serverIp=computingPlatformMapping1Ip;
        } else if (serverIp.equals(computingPlatform2Ip)) {
            serverIp=computingPlatformMapping2Ip;
        }

        String previewUrl = cameraPlaybackUrlUtil.getCameraPlaybackUrl(recordAlarmPO.getCameraCode(), simpleDateFormat.format(recordAlarmPO.getCreateTime()));
        HashMap<String, Object> res = new HashMap<>(16);
        res.put("url", previewUrl);
        res.put("serverIp", serverIp);
        return CommonResponse.ok(res);

    }

    @Override
    public CommonResponse batchSignError(List<RecordAlarmBO> recordAlarmBOList) {

        if (!CollectionUtils.isEmpty(recordAlarmBOList)) {

            ArrayList<RecordAlarmPO> updateRecordAlarmList = new ArrayList<>();

            for (RecordAlarmBO recordAlarmBO : recordAlarmBOList) {
                RecordAlarmBO alarmBO = new RecordAlarmBO();
                alarmBO.setId(recordAlarmBO.getId());
                alarmBO.setIsError(recordAlarmBO.getIsError());
                alarmBO.setReviewComments(recordAlarmBO.getReviewComments());
                alarmBO.setReviewUserId(SecurityUtils.getLoginUserId());
                RecordAlarmPO recordAlarmPo = RecordAlarmBO.convertBOToPO(alarmBO);
                updateRecordAlarmList.add(recordAlarmPo);

//                if (updateById(recordAlarmPO)) {
//                    return CommonResponse.ok("标记成功");
//                }
//                return CommonResponse.error("标记失败");
            }

            if (updateBatchById(updateRecordAlarmList)) {
                return CommonResponse.ok("标记成功");
            }
            return CommonResponse.error("标记失败");
        }else {
            throw new RuntimeException("标记图片不能为空");
        }


    }

    @Override
    public Integer countAlarmByCameraCodes(List<String> manageCameraCode) {

        long alarmSum = count(new QueryWrapper<RecordAlarmPO>().in("camera_code", manageCameraCode));


        return (int)alarmSum;
    }

    @Override
    public List<FunctionRecordNum> statisticsAlarmByType() {

        return  baseMapper.statisticsAlarmByType();
    }

    @Override
    public Integer getTodayRecordNum() {
        return  baseMapper.getTodayRecordNum();
    }

    @Override
    public Integer getWeekRecordNum() {
        return baseMapper.getWeekRecordNum();
    }

    @Override
    public void exportRecordExcel() {
        File folder = new File(recordExportPath);
        if (!folder.isDirectory()) {
            boolean mkdirs = folder.mkdirs();
        }
        String fileName = recordExportPath + "告警信息导出表格" + System.currentTimeMillis() + ".xlsx";
        List<RecordAlarmPO> recordAlarmPOList = this.list();

        List<RecordAlarmExcelVo> recordAlarmExcelVos = recordAlarmPOList.stream().map(item -> {
            RecordAlarmExcelVo recordAlarmExcelVo = new RecordAlarmExcelVo();
            BeanUtils.copyProperties(item, recordAlarmExcelVo);
//            try {
////                recordAlarmExcelVo.setPhotoUrl(new URL(item.getSnapPhoto()));
//            } catch (MalformedURLException e) {
//                throw new RuntimeException(e);
//            }
            recordAlarmExcelVo.setCreateTime(DateUtil.formatDateTime(item.getCreateTime()));
            return recordAlarmExcelVo;
        }).collect(Collectors.toList());

        EasyExcel.write(fileName, RecordAlarmExcelVo.class).sheet("告警信息")
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
//                .registerWriteHandler(new CustomCellWriteWidthConfig())
//                .registerWriteHandler(new CustomCellWriteHeightConfig())
//                .registerWriteHandler(EasyExcelUtils.getStyleStrategy())
                .doWrite(recordAlarmExcelVos);
    }

    @Override
    public List<RecordNumAndDetail.RecordDetail> getTodayRecordNumAndDetail(RecordInfoDto recordInfoDto) {
        List<String> cameraIdList = new LinkedList<>();
        if (null != recordInfoDto.getRegionBaseId()){
            cameraIdList = iRegionManageService.getBelowCameraIdList(recordInfoDto.getRegionBaseId());
        }else {
            cameraIdList = iRegionManageService.getBelowCameraIdList(SecurityUtils.getLoginRegionBaseId());
        }

        List<RecordNumAndDetail.RecordDetail>  recordDetails = baseMapper.getTodayRecordNumAndDetail(cameraIdList);

        return recordDetails;
    }

    @Override
    public List<RecordNumAndDetail.RecordDetail> getWeekRecordNumAndDetail(RecordInfoDto recordInfoDto) {
        List<String> cameraIdList = new LinkedList<>();
        if (null != recordInfoDto.getRegionBaseId()){
            cameraIdList = iRegionManageService.getBelowCameraIdList(recordInfoDto.getRegionBaseId());
        }else {
            cameraIdList = iRegionManageService.getBelowCameraIdList(SecurityUtils.getLoginRegionBaseId());
        }

        List<RecordNumAndDetail.RecordDetail>  recordDetails = baseMapper.getWeekRecordNumAndDetail(cameraIdList);



        return recordDetails;
    }

    @Override
    public Map<String, List<String>> getMonthRecordNumAndDetail(RecordInfoDto recordInfoDto) {
        List<String> cameraIdList = new LinkedList<>();
        if (null != recordInfoDto.getRegionBaseId()){
            cameraIdList = iRegionManageService.getBelowCameraIdList(recordInfoDto.getRegionBaseId());
        }else {
            cameraIdList = iRegionManageService.getBelowCameraIdList(SecurityUtils.getLoginRegionBaseId());
        }

        HashMap<String, List<String>> res = new HashMap<>();

        List<MonthAlarmNumAndDetail>  monthAlarmNumAndDetails = baseMapper.getMonthRecordNumAndDetail(cameraIdList);

        List<String> functionName = monthAlarmNumAndDetails.stream().map(MonthAlarmNumAndDetail::getAlarmName).collect(Collectors.toList());
        List<String> alarmNum = monthAlarmNumAndDetails.stream().map(MonthAlarmNumAndDetail::getNum).collect(Collectors.toList());

        res.put("functionName",functionName);
        res.put("alarmNum",alarmNum);


        return res;
    }

    @SneakyThrows
    @Override
    public void alarmExportExel(RecordAlarmPage page, HttpServletResponse response) {

        List<RecordAlarmExcelVo> resExcelVoList = new LinkedList<>();

        List<String> cameraIdList = new ArrayList<>();
        if (null == page.getCameraId()){
            if (StrUtil.isNotEmpty(page.getRegionBaseId())){
                //获取其组织下的所有摄像头id
                cameraIdList = iRegionManageService.getBelowCameraIdList(page.getRegionBaseId());
            }else {
                //获取当前登录用户下的所有设摄像头id
                cameraIdList = iRegionManageService.getBelowCameraIdList(SecurityUtils.getLoginRegionBaseId());
            }
        }

        resExcelVoList = baseMapper.alarmExportExel(page);

        List<RecordAlarmExcelVo> sortedList = resExcelVoList.stream()
                .sorted(Comparator.comparing(RecordAlarmExcelVo::getRegionName))
                .collect(Collectors.toList());

        String fileName =  "违规信息导出表格";

        EasyExcelUtils.export(fileName,sortedList,RecordAlarmExcelVo.class,response);
    }

    @Override
    public void coalMaintenanceAlarmExportExel(RecordAlarmPage page, HttpServletResponse response) {

    }

    @Override
    public CommonResponse getCameraPlaybackDownloadUrl(String recordId) {
        /**
         * 根据告警记录id，查找对应的摄像头
         */
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        RecordAlarmPO recordAlarmPO = this.getById(recordId);

        String serverIp = this.getServerIpByRecord(recordId);

        if (serverIp.equals(webServerIp)) {
            serverIp=webServerMappingIp;
        } else if (serverIp.equals(computingPlatform1Ip)) {
            serverIp=computingPlatformMapping1Ip;
        } else if (serverIp.equals(computingPlatform2Ip)) {
            serverIp=computingPlatformMapping2Ip;
        }

        String previewUrl = cameraPlaybackUrlUtil.getCameraPlaybackDownloadUrl(recordAlarmPO.getCameraCode(), simpleDateFormat.format(recordAlarmPO.getCreateTime()));
        HashMap<String, Object> res = new HashMap<>(16);
        res.put("url", previewUrl);
        res.put("serverIp", serverIp);
        return CommonResponse.ok(res);
    }

    /**
     * 获取服务器ip
     *
     * @param recordId
     * @return
     */
    private String getServerIpByRecord(String recordId) {

        return baseMapper.getServerIpByRecord(recordId);

    }


}
